﻿Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.String
Imports IDServer
Imports System.Text
Imports System.Collections
Imports CrystalDecisions.CrystalReports.Engine

''' <summary>
''' 銷售訂單統計報表
''' </summary>
''' <remarks>songrenhua</remarks>
Public Class Frm_SALSCReports
    Implements IDServer.IDServer.IDServer


    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp
    Private mDataset As DataSet
    Private SelectNode As TreeNode
    Private Img As ImageList
    Public bFind As Boolean
    '為設置報表的參數
    Private TabPage1date As String = Nothing
    Private tabpage5date As String = Nothing
    Private tabpage6date As String = Nothing
    '用來設置打印按鈕是否可以打印,在查詢之後值會改變，在切換TabPages時會判斷
    Private IsPrint As Boolean = False

    Private WithEvents MainForm As Frm_MainForm


    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

#Region "控制打印和導出按鈕是否可用"

    ''' <summary>
    ''' 設置按鈕狀態，和IsPrint一樣，在每次的點擊查詢或者TabPages改變后都要調用，獲取IsPrint的值
    ''' </summary>
    '''<param name="IsSetPrint" >獲取IsPrint的值，從而獲取是否可以打印和導出</param>
    ''' <remarks >SetButton(IsPrint)</remarks>
    Private Sub SetButton(ByVal IsSetPrint As Boolean)
        Try
            If IsSetPrint Then
                With MainForm
                    .ToolStripAdd.Enabled = False
                    .ToolStripEdit.Enabled = False
                    .ToolStripDelete.Enabled = False
                    .ToolStripSave.Enabled = False
                    .ToolStripCancel.Enabled = False
                    .ToolStripFirst.Enabled = False
                    .ToolStripLast.Enabled = False
                    .ToolStripNext.Enabled = False
                    .ToolStripPrivous.Enabled = False
                    .ToolStripExport.Enabled = IsSetPrint
                    .ToolStripImport.Enabled = False
                    .ToolStripPrint.Enabled = IsSetPrint
                    .ToolStripFilter.Enabled = True
                End With
            Else
                With MainForm
                    '.ToolStripExport.Enabled = False
                    '.ToolStripPrint.Enabled = False
                    '.ToolStripFilter.Enabled = False
                End With
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

#End Region

#Region "填充OrdeShopNo "
    ''' <summary>
    ''' 填充OrdeShopNo
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub OrdeShopNoItem()
        Try
            Dim Dset As New DataSet
            Dim sql As String = ""
            sql &= "select  distinct fShortName from BSC_StoreHouse  "
            Dset = Exec(sql, E_ExecType.DataSet)
            Me.OrdeShopNo.DataSource = Dset.Tables(0)
            Me.OrdeShopNo.DisplayMember = "fShortName"


        Catch ex As Exception
            MessageBox.Show("Initialize:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Sub
#End Region

    ''' <summary>
    ''' 填充狀態
    ''' </summary>
    ''' <remarks></remarks>

    Private Sub OrdeModeItem()
        Try
            Dim Dset As New DataSet
            Dim sql As String = ""
            sql &= "select ListA from BSC_OtherDefineB  where ItemNo = '16'"
            Dset = Exec(sql, E_ExecType.DataSet)
            Me.OrdeMode.DataSource = Dset.Tables(0)
            Me.OrdeMode.DisplayMember = "ListA"
            Me.ComboBox1.DataSource = Dset.Tables(0)
            Me.ComboBox1.DisplayMember = "ListA"


        Catch ex As Exception
            MessageBox.Show("Initialize:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Sub
#Region " "

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd

    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel

    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit

    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport
        Try
            If App.ExportEnable = False Then
                MessageBox.Show(My.resources.NotAllowExport, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If
            If (Me.TabControl1.SelectedTab.Name = TabPage1.Name) Then
                App.SaveXls(CType(Me.DGVPact.DataSource, DataTable))
            ElseIf (Me.TabControl1.SelectedTab.Name = TabPage5.Name) Then
                App.SaveXls(CType(Me.DGVClassified.DataSource, DataTable))
            ElseIf (Me.TabControl1.SelectedTab.Name = TabPage6.Name) Then
                App.SaveXls(CType(Me.DGVClassifiedDetial.DataSource, DataTable))
            End If
        Catch ex As Exception
            MessageBox.Show(My.resources.NotAllowExport, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    ''' <summary>
    ''' 這個地方需要有能夠判斷在那個界面，是否可以打印的函數
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint
        '判斷打印什麽，在哪一頁
        If (Me.TabControl1.SelectedTab.Name = TabPage1.Name) Then
            Me.SetPrint(Me.DGVPact, "SAL", "SaleOrde.rpt", "TextDateFromTo", Me.TabPage1date)
        ElseIf (Me.TabControl1.SelectedTab.Name = TabPage5.Name) Then
            '打印此頁的內容

            If Me.DGVClassified.Columns.Contains("ShopNo") Then
                Me.SetPrint(Me.DGVClassified, "SAL", "SaleOrdeShop.rpt", "TextDateFromTo", tabpage5date)
            ElseIf Me.DGVClassified.Columns.Contains("fEmployeeId") Then
                Me.SetPrint(Me.DGVClassified, "SAL", "SaleOrdeMan.rpt", "TextDateFromTo", tabpage5date)
            ElseIf Me.DGVClassified.Columns.Contains("fSaleDate") Then
                Me.SetPrint(Me.DGVClassified, "SAL", "SaleOrdeDate.rpt", "TextDateFromTo", tabpage5date)
            End If
        ElseIf (Me.TabControl1.SelectedTab.Name = TabPage6.Name) Then
            If (Me.DGVClassifiedDetial.Columns.Contains("ShopNo")) Then
                Me.SetPrint(Me.DGVClassifiedDetial, "SAL", "shop2.rpt", "TextDateFromTo", tabpage6date)
            ElseIf (Me.DGVClassifiedDetial.Columns.Contains("fEmployeeId")) Then
                Me.SetPrint(Me.DGVClassifiedDetial, "SAL", "SaleMan2.rpt", "TextDateFromTo", tabpage6date)
            ElseIf (Me.DGVClassifiedDetial.Columns.Contains("fSaleDate")) Then
                Me.SetPrint(Me.DGVClassifiedDetial, "SAL", "Date.rpt", "TextDateFromTo", tabpage6date)
            End If
        End If
    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave

    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function
#End Region

    Private Sub Frm_SALSCReports_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.OrdeShopNoItem()
        Me.OrdeModeItem()
        Me.OrdeMode.SelectedIndex = -1
        Me.OrdeShopNo.SelectedIndex = -1
        Find(False)
        BindDGV()

    End Sub

    Private Sub BindDGV()
        Try
            Dim SQLSTR As String
            Dim DSet As DataSet
            SQLSTR = " SELECT  '' AS SHOPNO,'' AS FSALEORDENO,'' AS FTAMOUNT FROM dbo.Sal_SaleOrdeA WHERE 1<>1; "
            SQLSTR += " SELECT '' AS fEmployeeId,'' AS fSaleOrdeNo,'' AS fWriteNo, '' AS fDeliverDate, "
            SQLSTR += " '' AS fGoodsType,'' AS fLinkMan,'' AS FTAmount FROM dbo.Sal_SaleOrdeA WHERE 1<>1 "

            DSet = Exec(SQLSTR, E_ExecType.DataSet)
            Me.DGVClassified.DataSource = DSet.Tables(0)
            BindDataGridViewCaption(Me.DGVClassified, Me.ReturnCaption(1))
            Me.DGVClassifiedDetial.DataSource = DSet.Tables(1)
            BindDataGridViewCaption(Me.DGVClassifiedDetial, Me.ReturnCaption(2))
        Catch ex As Exception

        End Try
    End Sub
    Private Function ReturnCaption(ByVal index As Integer) As Hashtable
        Dim Hash As New Hashtable

        Select Case index
            Case 1

                Hash.Add("SHOPNO", "門市")
                Hash.Add("FSALEORDENO", "銷售單數")
                Hash.Add("FTAMOUNT", "銷售總金額")

            Case 2
                Hash.Add("fEmployeeId", "銷售人員")
                Hash.Add("fSaleOrdeNo", "銷售單號")
                Hash.Add("fWriteNo", "手寫單號")
                Hash.Add("fDeliverDate", "送貨日期")
                Hash.Add("fGoodsType", "貨品類型")
                Hash.Add("fLinkMan", "聯繫人")
                Hash.Add("FTAmount", "總金額")
        End Select

        Return Hash
    End Function



#Region "合同資料統計 TabPage1 "
    ''' <summary>
    ''' 根據門店和單據狀態查找詳單(合同資料統計)
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub BtnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFind.Click
        Find(True)
    End Sub

    Private Sub Find(ByVal B As Boolean)
        Try

            Dim isFind As Boolean
            isFind = B

            Dim sql As New StringBuilder
            Dim whereExp As String
            Dim OrdeShopNo As String = Me.OrdeShopNo.Text
            Dim OrdeMode As String = Me.OrdeMode.Text
            Dim startDate As String = Me.StartDate.Text
            Dim endDate As String = Me.EndDate.Text
            If Me.StartDate.Value > Me.EndDate.Value Then
                startDate = Me.EndDate.Text
                endDate = Me.StartDate.Text
            End If

            sql.Append("SELECT     a.fSaleOrdeNo, a.fWriteNo, c.ListA AS fDeliverMode, q.fShortName AS fStoreCode, a.fDeliverDate, k.fCName AS fGoodsType, d.ListA AS fcustomerType, ")
            sql.Append(vbCrLf)
            sql.Append("a.fCustomerName AS fCustomerName,a.fLinkMan  AS fLinkMan,a.fLinkPhone AS fLinkPhone,a.fDeliverAddress AS fDeliverAddress,")
            sql.Append(vbCrLf)
            sql.Append("e.fShortName AS ShopNo,g.fCName AS fEmployeeId, a.fSaleDate, a.fOperaterMan, a.fOperateDate, a.fCheckMan, a.fCheckDate, h.ListA AS fOrdeStatus, n.FDSIA, n.FDSIB, n.FBSI,    ")
            sql.Append(vbCrLf)
            sql.Append("	a.FTAmount, n.FReceipt, n.FRefund, i.ListA AS fPayMode, a.fRemark   ")
            sql.Append(vbCrLf)
            sql.Append(" FROM         dbo.Sal_SaleOrdeA a LEFT JOIN ")
            sql.Append(vbCrLf)
            sql.Append("					  dbo.BSC_Customer b ON a.fCustomerID = b.Code LEFT JOIN ")
            sql.Append(vbCrLf)
            sql.Append("								  (SELECT b.ID, b.ItemNo, b.ListCode, b.ListA, b.ListB, b.ListC, b.ListD, b.ListE    ")
            sql.Append(vbCrLf)
            sql.Append("									FROM  dbo.BSC_OtherDefineA a INNER JOIN dbo.BSC_OtherDefineB b ON a.ID = b.ItemNo   ")
            sql.Append(vbCrLf)
            sql.Append("			WHERE a.ItemCode = 'SaleType') c ON a.fDeliverMode = c.ListCode LEFT  JOIN        ")
            sql.Append(vbCrLf)
            sql.Append("							  (SELECT b.ID, b.ItemNo, b.ListCode, b.ListA, b.ListB, b.ListC, b.ListD, b.ListE   ")
            sql.Append(vbCrLf)
            sql.Append("								FROM  dbo.BSC_OtherDefineA a INNER JOIN dbo.BSC_OtherDefineB b ON a.ID = b.ItemNo ")
            sql.Append(vbCrLf)
            sql.Append("								WHERE a.ItemCode = 'CustomerType') d ON a.fCustomerType = d.ListCode LEFT JOIN  ")
            sql.Append(vbCrLf)
            sql.Append("						  dbo.BSC_StoreHouse e ON a.ShopNo = e.fCode LEFT JOIN     ")
            sql.Append(vbCrLf)
            sql.Append("						  dbo.BSC_Employee g ON a.fEmployeeID = g.fCode LEFT JOIN     ")
            sql.Append(vbCrLf)
            sql.Append("							  (SELECT b.ID, b.ItemNo, b.ListCode, b.ListA, b.ListB, b.ListC, b.ListD, b.ListE  ")
            sql.Append(vbCrLf)
            sql.Append("								FROM  dbo.BSC_OtherDefineA a INNER JOIN  dbo.BSC_OtherDefineB b ON a.ID = b.ItemNo ")
            sql.Append(vbCrLf)
            sql.Append("								WHERE  a.ItemCode = 'BillstatusDefine') h ON a.fOrdeStatus = h.ListCode LEFT JOIN        ")
            sql.Append(vbCrLf)
            sql.Append("							  (SELECT a.ListCode, a.ListA FROM  dbo.BSC_OtherDefineB a inner join BSC_OtherDefineA b on b.ID=a.ItemNo   ")
            sql.Append(vbCrLf)
            sql.Append("								where b.ItemCode='Payterm') i ON a.fPayMode = i.ListCode LEFT JOIN      ")
            sql.Append(vbCrLf)
            sql.Append("							   dbo.BSC_GoodsType k ON a.fGoodsType = k.fCode LEFT JOIN       ")
            sql.Append(vbCrLf)
            sql.Append("						  dbo.BSC_AreaSet AS m ON a.fAreaID = m.ID LEFT JOIN         ")
            sql.Append(vbCrLf)
            sql.Append("						  (select * from Sal_InvoiceA where FType='DEPOSIT')n ON a.fSaleOrdeNo = n.FSaleOrdeNo LEFT JOIN       ")
            sql.Append(vbCrLf)
            sql.Append("						  dbo.BSC_StoreHouse AS q ON a.fStoreCode = q.fCode   ")


            If isFind = True Then
                whereExp = " where 1=1  and isnull(flag,'') <> 1  "
                If (Me.OrdeShopNo.Text.Trim <> "") Then
                    whereExp += " and e.fShortName='" & ModSys.Replace_Text(OrdeShopNo) & "'"
                End If
                If Me.OrdeMode.Text.Trim <> "" Then
                    whereExp += " and h.ListA='" & ModSys.Replace_Text(OrdeMode) & "'"
                End If
                If Me.StartDate.Text.Trim() <> "" And Me.EndDate.Text.Trim() <> "" Then
                    If Me.StartDate.Value <= Me.EndDate.Value Then
                        '  時間一定要加' 單引號，要不然使用between and的時候，sql server會默認把它轉化成int來比較，但是不能成功轉化成int，從而使得程序出錯
                        whereExp += "and fsaleDate between '" & Me.StartDate.Value.ToString("yyyy-MM-dd") & "' and '" & Me.EndDate.Value.ToString("yyyy-MM-dd") & "'"
                    ElseIf Me.StartDate.Value > Me.EndDate.Value Then
                        whereExp += "and fsaleDate between '" & Me.EndDate.Value.ToString("yyyy-MM-dd") & "' and '" & Me.StartDate.Value.ToString("yyyy-MM-dd") & "'"
                    End If
                End If
            Else
                whereExp = " where 1<>1  "
            End If

            sql.Append(whereExp)

            'Console.WriteLine(sql.ToString())
            'sql.Append("Exec [SaleOrde1]  '" & startDate & "','" & endDate & "','" & OrdeShopNo & "','" & OrdeMode & "' ")
            Dim Dtab As New DataTable
            Try
                Dtab = Exec(sql.ToString(), E_ExecType.DataTable)
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
            'If Not (Dtab Is Nothing) Then
            'If (Dtab.Rows.Count > 0) Then

            Try
                With Me.DGVPact
                    .Columns.Clear()
                    .AutoGenerateColumns = False
                    .Columns.Add("fSaleOrdeNo", "合同編號")
                    .Columns.Add("fWriteNo", "手寫單號")
                    .Columns.Add("fDeliverDate", "送貨日期")
                    .Columns.Add("fGoodsType", "單類")
                    .Columns.Add("fLinkMan", "聯系人")
                    .Columns.Add("FTAmount", "總金額")
                    .Columns("fSaleOrdeNo").DataPropertyName = "fSaleOrdeNo"
                    .Columns("fWriteNo").DataPropertyName = "fWriteNo"
                    .Columns("fDeliverDate").DataPropertyName = "fDeliverDate"
                    .Columns("fGoodsType").DataPropertyName = "fGoodsType"
                    .Columns("fLinkMan").DataPropertyName = "fLinkMan"
                    .Columns("FTAmount").DataPropertyName = "FTAmount"
                    .DataSource = Dtab
                End With
                'SaleOrde.rpt  報表
            Catch ex01 As Exception
                MessageBox.Show(ex01.Message)
            End Try
            'ElseIf (
            If isFind = True Then
                If Dtab.Rows.Count <= 0 Then
                    MessageBox.Show("沒有數據", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                End If

            End If

            IsPrint = Me.IsRecordsInDateV(Me.DGVPact)
            If (IsPrint) Then
                '獲取值提供給 報表中TextDateFromTo
                If (OrdeMode.Trim() <> "") Then
                    Me.TabPage1date = String.Concat("訂單狀態： ", OrdeMode, "   時間由：  ", startDate, "  到  ", endDate)
                Else
                    Me.TabPage1date = String.Concat("   時間由：  ", startDate, "  到  ", endDate)
                End If
            End If
            Me.SetButton(IsPrint)
            '  Else
            '   MessageBox.Show("數據讀取失敗", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            '   End If
        Catch ex As Exception

        End Try

    End Sub

#End Region


#Region "分類總計清單  TabPage5 "
    ''' <summary>
    ''' 分類總計清單
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub BtnFind5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFind5.Click

        If Me.ComboBox1.Text.Trim = "" Then
            MessageBox.Show("請選擇單據狀態！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            'Me.DGVClassified.Columns.Clear()
            IsPrint = Me.IsRecordsInDateV(DGVClassified)
            Me.SetButton(IsPrint)
            Exit Sub
        End If
        Dim DataViewColCaption As New StringBuilder
        Dim startDate As String = Nothing
        Dim endDate As String = Nothing
        Dim orderStatus As String = Me.ComboBox1.Text
        If Me.RBtnShop.Checked = True Then

            Dim sql As String = ""
            startDate = Me.DateTimePicker7.Text
            endDate = Me.DateTimePicker8.Text
            Dim OrdeMode As String = Me.ComboBox1.Text
            sql = "Exec [SaleOrdShop]  '" & startDate & "','" & endDate & "','" & OrdeMode & "' "
            Dim Dtab As New DataTable
            Try
                Dtab = Exec(sql, E_ExecType.DataTable)
            Catch ex As Exception
                MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Stop)
            End Try
            ' If (Dtab.Rows.Count > 0) Then
            Try
                '分類統計DataGrid數據填充
                '需要先清空列設置，然後再添加列，設置列名和列綁定的數據
                With Me.DGVClassified
                    .AutoGenerateColumns = False
                    .Columns.Clear()
                    .Columns.Add("ShopNo", "門市")
                    .Columns.Add("FSaleOrdeNo", "銷售單數")
                    .Columns.Add("FTAmount", "銷售金額數")
                    .Columns.Item(0).DataPropertyName = Dtab.Columns(0).ColumnName
                    .Columns.Item(1).DataPropertyName = Dtab.Columns(1).ColumnName
                    .Columns.Item(2).DataPropertyName = Dtab.Columns(2).ColumnName
                    .DataSource = Dtab
                End With
            Catch ex1 As Exception
                MessageBox.Show(ex1.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            End Try
            If (Dtab.Rows.Count <= 0) Then
                '' Me.DGVClassified.Columns.Clear()
                MessageBox.Show("沒有數據", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

            'Dim filename As String = ""
            'filename = GetReportPath("POS", "SaleOrdeShop.rpt")
        End If

        If Me.RBtnSaleMan.Checked = True Then

            Dim sql As String = ""
            startDate = Me.DateTimePicker7.Text
            endDate = Me.DateTimePicker8.Text
            Dim OrdeMode As String = Me.ComboBox1.Text
            sql = "Exec [SaleOrdMan]  '" & startDate & "','" & endDate & "','" & OrdeMode & "' "
            Dim Dtab As New DataTable
            Try
                Dtab = Exec(sql, E_ExecType.DataTable)
            Catch ex As Exception
                MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Stop)
            End Try

            ' If (Dtab.Rows.Count > 0) Then
            Try
                '分類統計DataGrid數據填充
                '需要先清空列設置，然後再添加列，設置列名和列綁定的數據
                With Me.DGVClassified
                    .AutoGenerateColumns = False
                    .Columns.Clear()
                    .Columns.Add("fEmployeeId", "銷售人員")
                    .Columns.Add("FSaleOrdeNo", "銷售單數")
                    .Columns.Add("FTAmount", "銷售金額數")
                    .Columns.Item(0).DataPropertyName = Dtab.Columns(0).ColumnName
                    .Columns.Item(1).DataPropertyName = Dtab.Columns(1).ColumnName
                    .Columns.Item(2).DataPropertyName = Dtab.Columns(2).ColumnName
                    .DataSource = Dtab
                End With
            Catch ex2 As Exception
                MessageBox.Show(ex2.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End Try
            If (Dtab.Rows.Count <= 0) Then
                '' Me.DGVClassified.Columns.Clear()
                MessageBox.Show("沒有數據", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
            'Dim filename As String = ""
            'filename = GetReportPath("POS", "SaleOrdeMan.rpt")

        End If
        If Me.RBtnSaleDate.Checked = True Then

            Dim sql As String = ""
            startDate = Me.DateTimePicker7.Text
            endDate = Me.DateTimePicker8.Text
            Dim OrdeMode As String = Me.ComboBox1.Text
            sql = "Exec [SaleOrdDate]  '" & startDate & "','" & endDate & "','" & OrdeMode & "' "
            Dim Dtab As New DataTable
            Try
                Dtab = Exec(sql, E_ExecType.DataTable)
            Catch ex As Exception
                MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            End Try

            '  If (Dtab.Rows.Count > 0) Then
            Try
                '分類統計DataGrid數據填充
                '需要先清空列設置，然後再添加列，設置列名和列綁定的數據
                With Me.DGVClassified
                    .AutoGenerateColumns = False
                    .Columns.Clear()
                    .Columns.Add("fSaleDate", "銷售日期")
                    .Columns.Add("FSaleOrdeNo", "銷售單數")
                    .Columns.Add("FTAmount", "銷售金額數")
                    .Columns.Item(0).DataPropertyName = Dtab.Columns(0).ColumnName
                    .Columns.Item(1).DataPropertyName = Dtab.Columns(1).ColumnName
                    .Columns.Item(2).DataPropertyName = Dtab.Columns(2).ColumnName
                    .DataSource = Dtab
                End With
            Catch ex3 As Exception
                MessageBox.Show(ex3.Message)
            End Try
            If (Dtab.Rows.Count <= 0) Then
                '' Me.DGVClassified.Columns.Clear()
                MessageBox.Show("沒有數據", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
            'Dim filename As String = ""
            'filename = GetReportPath("POS", "SaleOrdeDate.rpt")

        End If
        '設置是否可以打印
        IsPrint = Me.IsRecordsInDateV(DGVClassified)
        If (IsPrint) Then
            '獲取報表中的TextDateFromTo的值
            Me.tabpage5date = String.Concat("訂單狀態：  ", orderStatus, "       時間由：  ", startDate, "  到  ", endDate)
        End If
        Me.SetButton(IsPrint)
    End Sub
#End Region


#Region "分類統計詳單 TabPage6 "
    ''' <summary>
    ''' 分類統計詳單
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub BtnFindcount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFindcount.Click


        Dim startDate As String
        Dim endDate As String
        If Me.RadioButtonMan.Checked = True Then

            Dim sql As String = ""
            startDate = Me.DateTimePicker9.Text
            endDate = Me.DateTimePicker10.Text
            sql = "Exec [SaleOrde2]  '" & startDate & "','" & endDate & "' "
            Dim Dtab As New DataTable
            Try
                Dtab = Exec(sql, E_ExecType.DataTable)
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
            Dim filename As String = ""
            '  If (Dtab.Rows.Count > 0) Then
            Try
                With Me.DGVClassifiedDetial
                    .AutoGenerateColumns = False
                    .Columns.Clear()
                    .Columns.Add("fEmployeeId", "銷售人員")
                    .Columns.Add("fSaleOrdeNo", "合同編號")
                    .Columns.Add("fWriteNo", "手寫單號")
                    .Columns.Add("fDeliverDate", "送貨日期")
                    .Columns.Add("fGoodsType", "單類")
                    .Columns.Add("fLinkMan", "聯系人")
                    .Columns.Add("FTAmount", "總金額")
                    .Columns("fEmployeeId").DataPropertyName = "fEmployeeId"
                    .Columns("fSaleOrdeNo").DataPropertyName = "fSaleOrdeNo"
                    .Columns("fWriteNo").DataPropertyName = "fWriteNo"
                    .Columns("fDeliverDate").DataPropertyName = "fDeliverDate"
                    .Columns("fGoodsType").DataPropertyName = "fGoodsType"
                    .Columns("fLinkMan").DataPropertyName = "fLinkMan"
                    .Columns("FTAmount").DataPropertyName = "FTAmount"
                    .DataSource = Dtab
                End With
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
            If (Dtab.Rows.Count <= 0) Then
                ' Me.DGVClassifiedDetial.Columns.Clear()
                MessageBox.Show("沒有數據", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
            'filename = GetReportPath("POS", "shop2.rpt")

        End If

        If Me.RadioButtonShop.Checked = True Then

            Dim sql As String = ""
            startDate = Me.DateTimePicker9.Text
            endDate = Me.DateTimePicker10.Text
            sql = "Exec [SaleOrde2]  '" & startDate & "','" & endDate & "' "
            Dim Dtab As New DataTable
            Try
                Dtab = Exec(sql, E_ExecType.DataTable)
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
            ' If (Dtab.Rows.Count > 0) Then
            Try
                With Me.DGVClassifiedDetial
                    .AutoGenerateColumns = False
                    .Columns.Clear()
                    .Columns.Add("ShopNo", "門店")
                    .Columns.Add("fSaleOrdeNo", "合同編號")
                    .Columns.Add("fWriteNo", "手寫單號")
                    .Columns.Add("fDeliverDate", "送貨日期")
                    .Columns.Add("fGoodsType", "單類")
                    .Columns.Add("fLinkMan", "聯系人")
                    .Columns.Add("FTAmount", "總金額")
                    .Columns("ShopNo").DataPropertyName = "ShopNo"
                    .Columns("fSaleOrdeNo").DataPropertyName = "fSaleOrdeNo"
                    .Columns("fWriteNo").DataPropertyName = "fWriteNo"
                    .Columns("fDeliverDate").DataPropertyName = "fDeliverDate"
                    .Columns("fGoodsType").DataPropertyName = "fGoodsType"
                    .Columns("fLinkMan").DataPropertyName = "fLinkMan"
                    .Columns("FTAmount").DataPropertyName = "FTAmount"
                    .DataSource = Dtab
                End With
            Catch ex As Exception
                ' Me.DGVClassifiedDetial.Columns.Clear()
                MessageBox.Show(ex.Message)
            End Try
            If (Dtab.Rows.Count <= 0) Then
                MessageBox.Show("沒有數據", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
            'Dim filename As String = ""
            'filename = GetReportPath("POS", "SaleMan2.rpt")
        End If

        If Me.RadioButtonDate.Checked = True Then

            Dim sql As String = ""
            startDate = Me.DateTimePicker9.Text
            endDate = Me.DateTimePicker10.Text
            sql = "Exec [SaleOrde2]  '" & startDate & "','" & endDate & "' "
            Dim Dtab As New DataTable
            Try
                Dtab = Exec(sql, E_ExecType.DataTable)
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
            ' If (Dtab.Rows.Count > 0) Then
            Try
                With Me.DGVClassifiedDetial
                    .AutoGenerateColumns = False
                    .Columns.Clear()
                    .Columns.Add("fSaleDate", "銷售日期")
                    .Columns.Add("fSaleOrdeNo", "合同編號")
                    .Columns.Add("fWriteNo", "手寫單號")
                    .Columns.Add("fDeliverDate", "送貨日期")
                    .Columns.Add("fGoodsType", "單類")
                    .Columns.Add("fLinkMan", "聯系人")
                    .Columns.Add("FTAmount", "總金額")
                    .Columns(0).DataPropertyName = "fSaleDate"
                    .Columns("fSaleOrdeNo").DataPropertyName = "fSaleOrdeNo"
                    .Columns("fWriteNo").DataPropertyName = "fWriteNo"
                    .Columns("fDeliverDate").DataPropertyName = "fDeliverDate"
                    .Columns("fGoodsType").DataPropertyName = "fGoodsType"
                    .Columns("fLinkMan").DataPropertyName = "fLinkMan"
                    .Columns("FTAmount").DataPropertyName = "FTAmount"
                    .DataSource = Dtab
                End With
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
            If (Dtab.Rows.Count <= 0) Then
                'Me.DGVClassifiedDetial.Columns.Clear()
                MessageBox.Show("沒有數據", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
            'Dim filename As String = ""
            'filename = GetReportPath("POS", "Date.rpt")
        End If


        IsPrint = Me.IsRecordsInDateV(Me.DGVClassifiedDetial)
        If (IsPrint) Then
            '形式為 2008-11-17^StartDay&2008-11-17^StartDay,使用&分割兩個項目，使用^分割項目中的名字和值
            '這個選項是用來獲取統計報表的時間區段
            'Me.tabpage6date = String.Concat(startDate, "^StartDay", "&", endDate, "^EndDay^")
            Me.tabpage6date = String.Concat("時間由：  ", startDate, "  到  ", endDate)
        End If
        Me.SetButton(IsPrint)
    End Sub
#End Region



#Region "SetPrint 用於給actionprint()方法提供打印設置，設置好報表的登錄信息、文件路徑以及要更改的TextDateFromTo（textobject對象）的值"
    ''' <summary>
    ''' 用於給actionprint()方法提供打印設置
    ''' </summary>
    ''' <param name="DataGV">需要打印的數據來源，顯示在那個DataGridView</param>
    ''' <param name="modelName">當前所在的模塊，通過這個可以定位到模塊所在的報表文件夾</param>
    ''' <param name="reportName">報表文件名</param>
    ''' <remarks></remarks>
    Private Sub SetPrint(ByVal DataGV As System.Windows.Forms.DataGridView, ByVal modelName As String, ByVal reportName As String, ByVal TextObjectName As String, ByVal TextObjectValue As String)
        Dim Frm As New Frm_Wating()
        Dim mDT As DataTable
        Try
            If (DataGV.RowCount <= 0) Then
                MsgBox("對不起，沒有數據可列印！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Sub
            End If
            '登錄等待窗體
            Frm.Show()
            '獲取和設置報表登錄信息和路徑
            Dim myReportDoc As New CrystalDecisions.CrystalReports.Engine.ReportDocument
            Dim Pathstr As String = ""
            Pathstr = GetReportPath(modelName, reportName)
            myReportDoc.Load(Pathstr)
            ModSys.SetCrystalReportLoginfo(myReportDoc)

            '獲取報表數據源（將GridView的數據源轉化成DataTable，作為報表的數據源）
            mDT = CType(DataGV.DataSource, DataTable)
            myReportDoc.SetDataSource(mDT)
            With My.Forms.Frm_Report.CrystalReportViewer1
                .ReportSource = myReportDoc
                .Zoom(1)
                .DisplayGroupTree = False
            End With

            If Not TextObjectValue Is Nothing Then
                Me.setTextObject(myReportDoc, TextObjectName, TextObjectValue)
            End If
            Frm.Dispose()
            Frm_Report.ShowDialog()

        Catch ex As Exception
            MsgBox("對不起，打印出錯！" & ex.Message & ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            mDT = Nothing
        End Try
    End Sub
#End Region

    Private Sub TabControl1_Selecting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl1.Selecting
        '如果有數據，可以列印，否則，不可以列印(先設置成False,再判斷是否可以以便更新)
        IsPrint = False
        If Me.TabControl1.SelectedTab.Name = TabPage1.Name Then
            IsPrint = IsRecordsInDateV(Me.DGVPact)
            Me.SetButton(IsPrint)
        ElseIf Me.TabControl1.SelectedTab.Name = TabPage5.Name Then
            IsPrint = IsRecordsInDateV(Me.DGVClassified)
            Me.SetButton(IsPrint)
        ElseIf Me.TabControl1.SelectedTab.Name = TabPage6.Name Then
            IsPrint = IsRecordsInDateV(Me.DGVClassifiedDetial)
            Me.SetButton(IsPrint)
        End If
    End Sub

#Region "IsRecordsInDateV() "
    '判斷是否有數據在DataGridView中，從而決定是否允許打印
    Private Function IsRecordsInDateV(ByVal DataV As DataGridView) As Boolean
        Dim hasRecord As Boolean = False
        If DataV.Rows.Count > 0 Then
            hasRecord = True
        End If
        Return hasRecord
    End Function
#End Region



    Private Sub setTextObject(ByRef Report As ReportDocument, ByVal textObjectName As String, ByVal textObjectValue As String)
        Dim textobj As TextObject
        textobj = CType(Report.ReportDefinition.ReportObjects(textObjectName), TextObject)
        textobj.Text = textObjectValue
    End Sub



    Private Sub TabPage5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabPage5.Click

    End Sub

    Private Sub DGVPact_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGVPact.RowPostPaint, DGVClassified.RowPostPaint, DGVClassifiedDetial.RowPostPaint

        Try
            Dim DGView As DataGridView = DirectCast(sender, DataGridView)
            Dim SBrush As New SolidBrush(DGView.RowHeadersDefaultCellStyle.ForeColor)
            e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentCulture), e.InheritedRowStyle.Font, SBrush, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4)
        Catch ex As Exception
            MessageBox.Show("DataGridView_RowPostPaint:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub
End Class

